package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.PermissionDTO;
import com.lastproject.ejb.entities.Permission;
import com.lastproject.ejb.util.PermissionConversion;

/**
 * Lazar Mihnea
 */
@Stateless
public class PermissionDAO implements PermissionDAORemote {

	@PersistenceContext
	private EntityManager em;

	@EJB
	PermissionConversion conv;

	public PermissionDAO() {
	}

	@Override
	public void create(PermissionDTO entity) {
		em.persist(conv.fromDTO(entity));

	}

	@Override
	public void edit(PermissionDTO entity) {
		em.merge(conv.fromDTO(entity));

	}

	@Override
	public void remove(PermissionDTO entity) {
		Permission p = null;
		if ((p = em.find(Permission.class, conv.fromDTO(entity).getId())) == null) {
			// if ((p = super.find(entity.getCustomerId())) == null)
			// throw new Exception("Not found ID: "
			// + entity.getId());
			em.remove(em.merge(p));
		}
	}

	@Override
	public PermissionDTO findById(Object id) {
		Permission p = em.find(Permission.class, id);
		PermissionDTO perm = conv.fromEntity(p);
		return perm;
	}

	@Override
	public List<PermissionDTO> findAll() {
		List<Permission> pList = em.createQuery("SELECT p from Permission p", Permission.class).getResultList();
		List<PermissionDTO> pdtoList = new ArrayList<PermissionDTO>();
			for (Permission p : pList) {
				pdtoList.add(conv.fromEntity(p));
			}
		return pdtoList;
	}

}
